package com.mate.cloud.inventory.service;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class InventoryService {

    // 模拟库存数据库
    private static final Map<String, Integer> inventoryDB = new HashMap<>();

    // 初始化一些库存数据
    static {
        inventoryDB.put("product_001", 100);
        inventoryDB.put("product_002", 200);
        inventoryDB.put("product_003", 50);
    }

    /**
     * 扣减库存
     * @param productId 产品ID
     * @param quantity 扣减数量
     * @return 是否扣减成功
     */
    public boolean deductInventory(String productId, Integer quantity) {
        // 检查库存是否存在
        if (!inventoryDB.containsKey(productId)) {
            System.out.println("产品不存在: " + productId);
            return false;
        }

        // 检查库存是否充足
        int currentStock = inventoryDB.get(productId);
        if (currentStock < quantity) {
            System.out.println("库存不足! 产品: " + productId +
                    ", 当前库存: " + currentStock + ", 需要: " + quantity);
            return false;
        }

        // 扣减库存
        inventoryDB.put(productId, currentStock - quantity);
        System.out.println("库存扣减成功! 产品: " + productId +
                ", 扣减数量: " + quantity + ", 剩余库存: " + inventoryDB.get(productId));
        return true;
    }

    /**
     * 查询当前库存
     */
    public int getInventory(String productId) {
        return inventoryDB.getOrDefault(productId, 11);
    }
}
